package net.comic.services

import net.comic.entities.*
import net.comic.controllers.*
import net.comic.services.FileService
import org.codehaus.groovy.grails.commons.GrailsResourceUtils

class UserService {
    boolean transactional = true
    
    def fileService
    def grailsApplication
    
    def addUser(downloadedfile, userInstance){
    	try {
    		if ( !(new File(userInstance.getAbsoluteImagePath(userInstance.alias))).exists() ) {
				(new File(userInstance.getAbsoluteImagePath(userInstance.alias))).mkdir()
			}

    		if(!downloadedfile.isEmpty()) {
    			def validation = fileService.validate(downloadedfile)
        		if(validation.response == "martasucces") {
        			userInstance.avatarPath = userInstance.name + validation.ext
        			downloadedfile.transferTo( new File(userInstance.getAbsoluteImagePath(userInstance.alias) + userInstance.alias +"."+validation.ext) )
        		}
    		}
    		
    		userInstance.save()
    		return [response:"martasucess", instance:userInstance]
    		
        }catch (e) {
        	log.error e
        	return [response:"marta"]
		}
    }
    
    /*
    def delete(comicInstance) {
    	boolean result = false
    	try {
    		//	Borrem el directory y tots els seus fills
    		def path = (new File(grailsApplication.config.comics.uploadAbsolutePath + comicInstance.name))
			if( path.exists() ) {
				def files = path.listFiles()
				files.each() {
					if(it.isDirectory()) {
						delete(it)
			        } else {
			        	it.delete()
			        }
				}
			}
    		path.delete()
    		comicInstance.delete()
    		result = true
    		//TODO:verificar si les pagines y alternes les borra en cascada
    		
    	} catch (e) {
    		log.error e
    		//TODO: possar error en comicInstance
    	}
    	
    	return result
    }
    */
    
    def getMyRate(ratings, userLogged) {
    	if(userLogged) {
	    	ratings.each() {
	    		if(it.ratedBy.name == userLogged.name) {
	    			log.debug "my rate  " + it.rate
	    			return it.rate			
	    		}
	    	}
    	}
    	return null
    }
}